package com.huatai.bpmn.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.huatai.bpmn.constant.MinioBucket;
import com.huatai.bpmn.entity.FileEntity;
import com.huatai.bpmn.entity.dto.CandidateTaskDto;
import com.huatai.bpmn.entity.dto.PageDto;
import com.huatai.bpmn.service.*;
import com.huatai.bpmn.utils.Activiti7Util;
import com.huatai.common.api.R;
import com.huatai.common.config.MinioAPI;
import com.huatai.common.util.AuthUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.history.HistoricActivityInstance;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * @Author: nzj
 * @Date: 2023/7/7 11:03
 */
@RestController
@RequestMapping("/activiti")
@Api(value = "activiti流程控制", tags = "activiti流程控制")
public class ActivitiController {
	@Autowired
	private BasicLoadService basicLoadService;

	@Autowired
	private TbBusinessService businessService;


	@Autowired
	private BasicDataService basicDataService;

	@Autowired
	private FileService fileService;

	@Autowired
	private MinioAPI minioAPI;

	@Autowired
	private ExternalParameterService externalParameterService;

	/**
	 * 部署流程定义 文件上传方式部署流程定义
	 * @param file bpmn文件
	 * @param deployName 部署名称
	 * @param externalParameterId 绑定表单标识
	 * @return
	 * @throws IOException
	 */
	@PostMapping("/deploy")
	@ApiOperation("部署流程定义,文件上传方式部署流程定义")
	public R<Map<String, Object>> deployment(@RequestBody MultipartFile file, @RequestParam String deployName,
								 @RequestParam String externalParameterId) throws IOException {
		return businessService.deploy(file,deployName,externalParameterId);
	}

	/**
	 * 查看部署流程集合
	 */
	@PostMapping("getDeployList")
	@ApiOperation("查看部署流程集合")
	@ApiOperationSupport(includeParameters = {
		"pageDto.page",
		"pageDto.limit"
	})
	public  R<Map<String, Object>> getDeployList(@RequestBody PageDto pageDto) {
		return businessService.getDeployList(pageDto);
	}


	/**
	 * 根据部署id查询对应的表单
	 */
	@PostMapping("/findDeployFormById")
	@ApiOperation("根据部署id查询对应的表单")
	public  R<JSONObject> findDeployFormById(@RequestParam String deploymentId){
		return businessService.findDeployFormById(deploymentId);
	}

	/**
	 * 创建流程定义
	 */
	@PostMapping("/definition")
	@ApiOperation("创建流程定义")
	public  R<Map<String, Object>> startProcess(@RequestBody JSONObject jsonObject){
		String myKey = jsonObject.getString("definitionKey");

		return Activiti7Util.startProcessInstanceByKey(myKey,jsonObject,businessService,fileService,basicLoadService,externalParameterService);
//		return Activiti7Util.startTask(myKey,jsonObject,businessService,fileService,basicLoadService,externalParameterService);
	}


	/**
	 * 查询待办任务列表
	 * @return
	 */
	@PostMapping("/findToDoTask")
	@ApiOperation("查询待办任务列表")
	@ApiOperationSupport(includeParameters = {
		"candidateTaskDto.userId",
		"candidateTaskDto.page",
		"candidateTaskDto.limit"
	})
	public R<Map<String, Object>> findToDoTask(@RequestBody CandidateTaskDto candidateTaskDto){
		return businessService.findToDoTask(candidateTaskDto);
	}


	/**
	 * 查询已办任务列表
	 */
	@PostMapping("/findCompleteTask")
	@ApiOperation("查询已办任务列表")
	@ApiOperationSupport(includeParameters = {
		"candidateTaskDto.userId",
		"candidateTaskDto.page",
		"candidateTaskDto.limit"
	})
	public R<Map<String,Object>> findCompleteTask(@RequestBody CandidateTaskDto candidateTaskDto){
		return businessService.findCompleteTask(candidateTaskDto);
	}

	/**
	 * 查询当前用户已发起的申请
	 */
	@PostMapping("/findOneselfApplication")
	@ApiOperation("查询当前用户已发起的申请")
	@ApiOperationSupport(includeParameters = {
		"candidateTaskDto.userId",
		"candidateTaskDto.page",
		"candidateTaskDto.limit"
	})
	public R<Map<String, Object>> findOneselfApplication(@RequestBody CandidateTaskDto candidateTaskDto){
		return businessService.findOneselfApplication(candidateTaskDto);
	}

	/**
	 * 获取当前用户已关注的流程发起信息
	 */
	@PostMapping("/findOneselfApplicationAndDeployment")
	@ApiOperation("获取当前用户已关注的流程发起信息")
	@ApiOperationSupport(includeParameters = {
		"candidateTaskDto.deployKey",
		"candidateTaskDto.page",
		"candidateTaskDto.limit"
	})
	public R<Map<String, Object>> findOneselfApplicationAndDeployment(@RequestBody CandidateTaskDto candidateTaskDto){
		candidateTaskDto.setUserId(AuthUtil.getUser().getUserId().toString());
		return businessService.findOneselfApplicationAndDeployment(candidateTaskDto);
	}

	/**
	 * 查询所有已完成的任务
	 */
	@PostMapping("/selectCompleteTaskAll")
	@ApiOperation("查询所有已完成的任务")
	@ApiOperationSupport(includeParameters = {
		"candidateTaskDto.page",
		"candidateTaskDto.limit",
		"candidateTaskDto.deployKey"
	})
	public R<Map<String, Object>> selectCompleteTaskAll(@RequestBody CandidateTaskDto candidateTaskDto){
		return businessService.selectCompleteTaskAll(candidateTaskDto);
	}

	/**
	 * 查看流程实例的历史处理信息
	 */
	@PostMapping("/taskHistoryInfo")
	@ApiOperation("查看流程实例的历史处理信息")
	@ApiOperationSupport(includeParameters = {
		"candidateTaskDto.procinstId"
	})
	public R<Map<String, Object>> taskHistoryInfo(@RequestBody CandidateTaskDto candidateTaskDto){
		return businessService.taskHistoryInfo(candidateTaskDto);
	}

	/**
	 * 完成任务
	 */
	@ApiOperation("完成任务")
	@PostMapping("/completeTask")
	public  R<Boolean> completionTask(@RequestBody JSONObject jsonObject){
		return businessService.fulfilTask(jsonObject);
	}

	/**
	 * 根据id删除流程实例
	 * @param processInstanceId
	 * @param reason 原因
	 * @return
	 */
	@ApiOperation("根据id删除流程实例")
	@GetMapping("/removeFlowInstance")
	public R<String> removeFlowInstance(@RequestParam String processInstanceId,@RequestParam String reason){
		return businessService.removeFlowInstance(processInstanceId,reason);
	}

	/**
	 * 获取部署的流程图
	 */
	@ApiOperation("获取部署的流程图")
	@PostMapping("/getDeploymentFlowChart")
	public void getDeploymentFlowChart( @RequestParam String definitionKey, HttpServletResponse response) throws IOException {
		businessService.getDeploymentFlowChart(definitionKey,response);
	}

	/**
	 * 根据流程实例id查询对应的流程部署id
	 */
	@ApiOperation("根据流程实例id查询对应的流程部署id")
	@GetMapping("/getDeploymentId")
	public R getDeploymentId(@RequestParam String processInstanceId){
		return businessService.getDeploymentId(processInstanceId);
	}

	@ApiOperation("获取节点数据")
	@GetMapping("/getNodeData")
	public R<JSONObject> getNodeData(@RequestParam("processInstanceId") String processInstanceId){
		return R.data(businessService.getNodeData(processInstanceId));
	}

	@ApiOperation("文件上传")
	@ApiOperationSupport(order = 1)
	@PostMapping("/upload")
	public R uploadFile(@ApiParam(name = "file", value = "文件上传字段", required = true) MultipartFile file,String fileType){
		try {
			minioAPI.makeBucket(MinioBucket.BPMN_FILES);
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			LocalDate now = LocalDate.now();
			String dateFormat = now.format(formatter);
			//给文件和图片重新命名
			FileEntity fileEntity = new FileEntity();
			long id = IdWorker.getId(fileEntity);
			String fileName = dateFormat+"/"+ id + file.getOriginalFilename();
			minioAPI.uploadInputStream(MinioBucket.BPMN_FILES, fileName, file.getInputStream(), file.getContentType());
			fileEntity.setId(id);
			fileEntity.setFilePath(fileName);
			fileEntity.setFileType(fileType);
			fileEntity.setDeleted(true);
			fileService.save(fileEntity);
			return R.data(fileName);
		}catch (Exception e){
			return R.fail("文件上传失败");
		}
	}

	@PostMapping("/downloadFile")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "下载文件")
	public void downloadFile(@ApiParam(value = "文件路径", required = true) @RequestParam String url, HttpServletResponse response) {
		try {
			// 获取文件对象
			InputStream object = minioAPI.download(MinioBucket.BPMN_FILES, url);
			byte buf[] = new byte[1024];
			int length = 0;
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(url.substring(url.lastIndexOf("/") + 1), "UTF-8"));
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			OutputStream outputStream = response.getOutputStream();
			// 输出文件
			while ((length = object.read(buf)) > 0) {
				outputStream.write(buf, 0, length);
			}
			// 关闭输出流
			outputStream.close();
		} catch (Exception ex) {
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			String data = "文件下载失败";
			OutputStream ps = null;
			try {
				ps = response.getOutputStream();
				ps.write(data.getBytes("UTF-8"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@PostMapping("/downloadFileSign")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "下载文件（加密）")
	public R<String> downloadFileSign(@ApiParam(value = "文件路径", required = true) @RequestParam String url, HttpServletResponse response) {
		try {
			// 获取文件对象
			String signedUrl = minioAPI.getSignedUrl(MinioBucket.BPMN_FILES, url,1800);
			return R.data(signedUrl);
		} catch (Exception ex) {
			return R.fail("获取文件地址失败");
		}
	}

}
